<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Get_page extends CI_Controller {

    /**
     * Crawl Weibo Content And Info By Keyword
     *
     */
    public $_log_dir    = 'get_page';
    public $_result_dir = 'result';
    public $_return_data;
    const ERROR_TAB     = 'error';
    const LOG_LEVEL_ERROR = 'error';
    const LOG_LEVEL_WARING = 'waring';
    const LOG_LEVEL_NOTICE = 'notice';

    public function __construct(){
        parent::__construct();
        $this->load->helper('MY_auth_verification');
        $this->load->library('error_code_library');
        $this->load->library('crawl_abstract');
        $this->load->database();
        $this->_return_data = $this->config->item('return_data');
    }

    public function index(){
		$this->crawl();
	}

    public function crawl() {
        $auth_verification_result = authentication($this, $this->input->get_post(NULL,TRUE));
        if(is_array($auth_verification_result) && array_key_exists(self::ERROR_TAB,$auth_verification_result)) {
            echo json_encode($auth_verification_result);
            exit;
        } else {
            $validate_result = url_validate($this, $this->input->get_post(NULL,TRUE));

            if(is_array($validate_result) && array_key_exists(self::ERROR_TAB,$validate_result)) {
                echo json_encode($auth_verification_result);
                exit;
            } else {
                $this->execute_crawl();
            }
        }
    }

    private function execute_crawl() {
        $this->load->library('crawl_html_library');
        $this->load->library('Crawl_html_by_url_library');
        $html_crawl_result = $this->crawl_html_by_url_library->crawl();
        if(is_array($html_crawl_result) && array_key_exists(self::ERROR_TAB, $html_crawl_result)) {
            echo json_encode($html_crawl_result);
        } else {
            if(is_array($html_crawl_result) && array_key_exists('result', $html_crawl_result)){
                echo $html_crawl_result['result'];
            } else {
                echo $html_crawl_result;
            }
        }
    }
}
